#include "grepticinohousesobjekt.h"

#include "strutturaicone.h"


GrepTicinoHousesObjekt::GrepTicinoHousesObjekt( QObject * parent )
{
	CastParent = parent;
	TmpLog = "Init\n";
	cityId = 0;
	CalendarShow = false;
	
	Traduzionexx = TraduzioneIconeValidate();
    Numerazionexx = NumerazioneIconeValidate();
	////////int numero_mio = Traduzionexx.value(numeroremoto);
    /*  folle */
	
}

bool GrepTicinoHousesObjekt::Load( const QString stream , const int dbid , int tipo ) 
{
	 UPDATE_SQL_LINE = "";       /////   imageNames
	 cityId = 0;
	 CalendarShow = false;
	 immagini.clear();
	 bool cangrep = SetStream(stream);
	 ///////////qDebug() << "### Load  " << cangrep;
	 if (!cangrep) {
		return false;
	 }
	 int annoadesso = QDateTime::currentDateTime().date().year();
	 attislist.clear();
	 dbnames.clear();
	 riservati.clear();
	 NewattributesTicino.clear();
	 QString name,url,dir,tel1,tel2;
	  QDomElement root = documentElement();
	  QDomElement d1 = root.firstChildElement("S:Body");
	  QDomElement d2 = d1.firstChildElement("ns2:getHouseResponse");
	  QDomElement r = d2.firstChildElement("return");
	  QDomElement ra = r.firstChildElement("address");
	 QString adresseEsterno;
	 QString cpaEsterno;
	 int cpaFuori;
	 int user = ra.firstChildElement("addressId").text().toInt();
	 ////////qDebug() << "### UPDATE_SQL_LINE A " << user;
	 /////////qDebug() << "### UPDATE_SQL_LINE B" << dbid;
	 if (user < 1) {
		 return false;
	 }
	 if (dbid != user) {
		 return false;
	 }
	 iltuoCal.InitRange(annoadesso,annoadesso + 1,user);
	 //////qDebug() << "### giorniveri "  << iltuoCal.visual_day.size();
	 const int livello = r.firstChildElement("itemState").firstChildElement("itemStateId").text().toInt();
	 
	 ////////////////qDebug() << "### livello  " << livello;
	 
	 if (livello == 100) {
		 dbnames.insert("TAX_01","A");
	 } else if (livello == 300) {
		 dbnames.insert("TAX_01","B");
	 } else if (livello == 400) {
		 dbnames.insert("TAX_01","C");
	 } else {
		 return false;
	 }
	 cityId = ra.firstChildElement("city").firstChildElement("cityId").text().toInt();
	 //////QString MMpaese; /////ra.firstChildElement("city").firstChildElement("cityId").text() + " " +
	                   /////ra.firstChildElement("city").firstChildElement("description_I").text() + " " +
	                   /////ra.firstChildElement("city").firstChildElement("zip").text();
		dbnames.insert("RISE_46",QString("CityId di Ticino Turismo = %1").arg(cityId));
	 /*
	 <address>
                         <addressId>20770</addressId>
                         <city>
                              <cityId>249</cityId>
                              <description_D>Piano di Peccia</description_D>
                              <description_E>Piano di Peccia</description_E>
                              <description_F>Piano di Peccia</description_F>
                              <description_I>Piano di Peccia</description_I>
                              <zip>6695</zip>
                         </city>
	 */
	 dbnames.insert("TXT_100",toBase64(stream ));
	 
	 
	 QString notaMemo = _NOTA_REGISTRO_CALENDARIO_ + " - " + QDateTime::currentDateTime().toString();
	 dbnames.insert("NOTE_95",toBase64(notaMemo));
								GrepAttributesItem(r);
								
								const int CPAVero = ra.firstChildElement("city").firstChildElement("zip").text().toInt();
								const QString paesevalle = ra.firstChildElement("city").firstChildElement("description_I").text();
	 
	 
	             if (r.firstChildElement("webSiteUrl").text().size() > 3) {
							        QUrl surl = QUrl(r.firstChildElement("webSiteUrl").text());
							        url = surl.host();
								      dbnames.insert("WWW_11",url);
						    }
								if (r.firstChildElement("description_D").text().size() > 3) {
							        dbnames.insert("TXTDE_102",toBase64(r.firstChildElement("description_D").text()));
						    }
								if (r.firstChildElement("description_I").text().size() > 3) {
							        dbnames.insert("TXTIT_101",toBase64(r.firstChildElement("description_I").text()));
						    }
								if (r.firstChildElement("description_F").text().size() > 3) {
							        dbnames.insert("TXTFR_103",toBase64(r.firstChildElement("description_F").text()));
						    }
								if (r.firstChildElement("description_E").text().size() > 3) {
							        dbnames.insert("TXTEN_104",toBase64(r.firstChildElement("description_E").text()));
						    }
								if (r.firstChildElement("description_D").text().size() > 3) {
							        dbnames.insert("TXTDE_102",toBase64(r.firstChildElement("description_D").text()));
						    }
								if (ra.firstChildElement("emailUrl").text().contains("@")) {
							        dbnames.insert("MAIL_10",ra.firstChildElement("emailUrl").text());
						    }
								if (r.firstChildElement("ownerAddress").text().size() > 3) {
							        dbnames.insert("VIA_14",r.firstChildElement("ownerAddress").text());
						    }
								
                            if (r.firstChildElement("ownerPhone").text().size() > 3) {
									dbnames.insert("TEL_7",PhoneRegX(r.firstChildElement("ownerPhone").text()));
						    }
								if (r.firstChildElement("ownerMobile").text().size() > 3) {
									dbnames.insert("NATEL_12",PhoneRegX(r.firstChildElement("ownerMobile").text()));
						    }
								
								
								
								
								
								if (r.firstChildElement("ownerFax").text().size() > 3) {
									dbnames.insert("FAX_9",PhoneRegX(r.firstChildElement("ownerFax").text()));
						    }
								if (ra.firstChildElement("phone").text().size() > 3 && 
									  ra.firstChildElement("phone").text() != r.firstChildElement("ownerPhone").text() ) {
									  dbnames.insert("TEL_8",PhoneRegX(ra.firstChildElement("phone").text()));
						    }
                            
                double Pmass = qMax (r.firstChildElement("ratePerPersonMax").text().toDouble(),r.firstChildElement("ratePerPersonMin").text().toDouble());
                double Pmin = qMin (r.firstChildElement("ratePerPersonMax").text().toDouble(),r.firstChildElement("ratePerPersonMin").text().toDouble());
								
                double Cmass = qMax (r.firstChildElement("ratePerDayMin").text().toDouble(),r.firstChildElement("ratePerDayMax").text().toDouble());
                double Cmin = qMin (r.firstChildElement("ratePerDayMin").text().toDouble(),r.firstChildElement("ratePerDayMax").text().toDouble());
								
								if (Cmass > 0) {
									dbnames.insert("MAX_C",QString("%1").arg(Cmass, 0, 'f', 2));
								}
								if (Cmin > 0) {
									dbnames.insert("MIN_C",QString("%1").arg(Cmin, 0, 'f', 2));
								}
								
                                if (Pmass > 0) {
									dbnames.insert("MAX_P",QString("%1").arg(Pmass, 0, 'f', 2));
								}
								if (Pmin > 0) {
									dbnames.insert("MIN_P",QString("%1").arg(Pmin, 0, 'f', 2));
								}
								
								
								QStringList attislist_50;
								QStringList attislist_60;
								QStringList attislist_70;
								
								////////qDebug() << "### NewattributesTicino.size() " << NewattributesTicino.size();
								
								 QMapIterator <int,IcoAttTi> att(NewattributesTicino);
                 while (att.hasNext()) {
                       att.next();
									          IcoAttTi Dare = att.value(); 
									          if (Dare.Gid == 30) {
															attislist_50.append(QString("%1").arg(att.key()));
														} else if (Dare.Gid == 20) {
															attislist_70.append(QString("%1").arg(att.key()));
														} else {
															attislist_60.append(QString("%1").arg(att.key()));
														}
                 }
								 
								if (attislist_50.size() > 0) {
									dbnames.insert("ATT_50",attislist_50.join("/"));
						    }
								if (attislist_60.size() > 0) {
									dbnames.insert("ATT_60",attislist_60.join("/"));
						    }
								if (attislist_70.size() > 0) {
									dbnames.insert("ATT_70",attislist_70.join("/"));
						    }
								
								const int stelle = r.firstChildElement("category").firstChildElement("categoryId").text().toInt();
								if (stelle > 0) {
									dbnames.insert("STAR_3",QString("%1").arg(stelle));
								}
								
								if (r.firstChildElement("dateRange").text() != "false") {
									/////////qDebug() << "### Calendario Si ";
									dbnames.insert("SHOW_CAL","1");
									CalendarShow = true;
									/////////qDebug() << "### riservati =  "  << riservati.size();
								} else {
									/////////////qDebug() << "### Calendario No ";
								}
								
								
								dbnames.insert("NOME_2",r.firstChildElement("denomination_I").text());
								dbnames.insert("LETTI_31",r.firstChildElement("numberBeds").text());
								dbnames.insert("CAME_30",r.firstChildElement("numberRooms").text());
								dbnames.insert("DIR_6 ",r.firstChildElement("ownerName").text());
								
								if (r.firstChildElement("ownerCity").text().size() > 3) {
									adresseEsterno = r.firstChildElement("ownerCity").text();
									cpaEsterno = PhoneRegX(adresseEsterno);
	                cpaFuori = cpaEsterno.toInt();
									if (cpaFuori > 0 && cpaFuori !=CPAVero) {
									 /* indirizzo fuori luogo !!!! */
									  //////qDebug() << "### cpaEsterno " << cpaEsterno << "|" << cpaFuori;
										dbnames.insert("E_PAESE_800",adresseEsterno);
										dbnames.insert("E_VIA_800",dbnames.take("VIA_14"));
										dbnames.insert("VIA_14","");
										
									}
								}
								
								 if (dbnames.size() < 2) {
									return false;
								 }
	 return true;
}








bool GrepTicinoHousesObjekt::Indexing( const QString stream , int oggtipo )
{
	TmpLog += "Indexing\n";
	bool cangrep = SetStream(stream);
	 /////////qDebug() << "### Load  " << cangrep;
	 if (!cangrep) {
		return false;
	 }
	 QString ListaNome,ListaTutto;
	 nomiidticino.clear();
	 
	  QDomElement root = documentElement();
	  QDomElement d1 = root.firstChildElement("S:Body");
	  QDomElement d2 = d1.firstChildElement("ns2:findLightHousesResponse");
	   QDomElement child = d2.firstChildElement("return");
	   int con = 0;
        while (!child.isNull()) { 
					const int casa = child.firstChildElement("itemTypeId").text().toInt();
					const int tipo = child.firstChildElement("stateId").text().toInt();
					
				 if (casa == oggtipo) {
					//////////qDebug() << "### item "  << tipo; 
					if (tipo == 300 || tipo == 400 || tipo == 100) {
					con++;
						QDateTime timer1( QDateTime::currentDateTime() ); 
					QString title = child.firstChildElement("denomination").text(); 
					int IDNumero = child.firstChildElement("itemId").text().toInt(); 
					int regioneidTicino = child.firstChildElement("zip").text().toInt(); 
					QString city = child.firstChildElement("city").text();
						QString NNr = QString("Pos.%2,Nr.%1").arg(IDNumero).arg(con);
						///////////qDebug() << "### item "  << title << "-" << city << "-" << IDNumero << "-" << regioneidTicino;
						nomiidticino.insert(IDNumero,child.firstChildElement("zip").text());
						 ListaTutto.append("Log Lista entrata:"+timer1.toString(Qt::SystemLocaleDate)+","+NNr+",Stato/" + child.firstChildElement("stateId").text()  + ","+city+","+child.firstChildElement("zip").text()+","+title+"\n");
					}
					
				}
					
					child = child.nextSiblingElement("return"); 
					
				}
				
				/////////QMapIterator <int,QString> d(nomiidticino);
                //////// while (d.hasNext()) {
                      /////////// d.next();
									    ///////// qDebug() << "### r " << d.key() << "|" << d.value();
									    /////// ListaNome.append(QString("%1,%2\n").arg(d.value()).arg(d.key()));
                //////// }
	    TmpLog += ListaTutto;
	  ///////fwriteutf8("listacase.txt",ListaTutto);
	 ////////////fwriteutf8("Idpaesi.txt",ListaNome);
	 
	
}




void  GrepTicinoHousesObjekt::GrepAttributesItem( const QDomElement e )
{
	
	             QDomNode chi = e.firstChild();
                   while ( !chi.isNull() ) {
                       if ( chi.isElement() ) {
                        QDomElement tag = chi.toElement();
												 if (tag.tagName() == _TAG_ATTRIBUTI_ && tag.text().toInt() > 100 )  {
													       if (!attislist.contains(tag.text())) {
																	  attislist.append(tag.text());
																	  //////qDebug() << "### inaTT " << tag.text();
																 }
												 } else if (tag.tagName() == _RADICE_ATTRIBUTI_ ) {
													 GrepNewAttributes(tag);
													 GrepAttributesItem(tag);
												 } else if (tag.tagName() == "imageNames" ) {
													 if (!immagini.contains(tag.text())) {
														  immagini.append(tag.text());
													 }
                                                     /*  gg gg */
													 GrepAttributesItem(tag);
													 GrepCalendars(tag);
												 } else {
													 GrepAttributesItem(tag);
													 GrepCalendars(tag);
												 }
                       } 
                     chi = chi.nextSibling();            
                   }
}

/*

UPDATE_SQL_LINE = "";       /////   imageNames
	 cityId = 0;
	 immagini.clear();

*/


void  GrepTicinoHousesObjekt::GrepNewAttributes( const QDomElement e )
{
						if (e.tagName() != _RADICE_ATTRIBUTI_) {
							return;
						}
						IcoAttTi concater;
						const int gruppo = e.firstChildElement("attributeGroup")
																.firstChildElement("attributeGroupId").text().toInt();
						QString nome = e.firstChildElement("attributeGroup")
																.firstChildElement("description_I").text();
						concater.Gid = gruppo;
						concater.nameG = nome;
						concater.it = e.firstChildElement("description_I").text();
						concater.de = e.firstChildElement("description_D").text();
						concater.fr = e.firstChildElement("description_F").text();
						concater.en = e.firstChildElement("description_E").text();
						int numeroremoto = e.firstChildElement(_TAG_ATTRIBUTI_).text().toInt();
						const int numero_mio = Traduzionexx.value(numeroremoto);
						concater.id = numero_mio;
						
						
						/////////qDebug() << "### concater " << numero_mio << " " << numeroremoto;
						if (concater.id > 0) {
						NewattributesTicino.insert(concater.id,concater);
						}
	
}
void  GrepTicinoHousesObjekt::GrepCalendars( const QDomElement e )
{
	if (e.tagName() != _DATE_TAG_CALENDAR_) {
	return;
	}
	const int liberono = e.firstChildElement("stateId").text().toInt();
	if (liberono !=1) {
	return;
	}
	QDate start = DateFromUtc(e.firstChildElement("fromDate").text());
	QDate stop = DateFromUtc(e.firstChildElement("untilDate").text());
	int annoadesso = QDateTime::currentDateTime().date().year();
	if (start.year() < annoadesso ) {
	return;
	}
	/////////qDebug() << "### liberono " << liberono;
	//////////qDebug() << "### start" << start;
	/////////////qDebug() << "### stop " << stop;
	
	DayCell master;
	        master.dax = start;
	DayCell slave;
	        slave.dax = stop;
					int parti = master.fromUday();
	        int ferma = slave.fromUday() + 1;
	        for (int i=parti; i<ferma; i++) {
						 DayCell oggettodata = iltuoCal.TakeItem(i);
						         oggettodata.modus = 3;
						         oggettodata.note.clear();
						 riservati.insert(i,oggettodata);
					}
}









/* <attributes>
                         <attributeGroup>
                              <attributeGroupId>30</attributeGroupId>
                              <description_F/>
                              <description_I>posizione</description_I>
                         </attributeGroup>
                         <attributeId>1043</attributeId>
                         <description_D>zentrale Lage</description_D>
                         <description_E>central position</description_E>
                         <description_F>position centrale</description_F>
                         <description_I>posizione centrale</description_I>
                    </attributes>
*/












